package tolgahan.albayrak.as3.reflection
{
	import flash.events.IEventDispatcher;
	
	import tolgahan.albayrak.as3.reflection.events.PropertyChangeEvent;
	

	public class VariableInfo extends TypedMemberInfo
	{
		public function VariableInfo(xml:XML, baseType:Type, memberIndex:uint)
		{
			super(xml, baseType, memberIndex);
		}
		
		public function getValue(source:Object):*
		{
			if(source is _baseType.classReference)
				return source[_name];
		}
		public function setValue(source:Object, value:*, dispatchPropertyChange:Boolean = true):Boolean
		{
			if(validate(value) && (source is _baseType.classReference))
			{
				if(dispatchPropertyChange && (source is IEventDispatcher))
				{
					var old:* = source[_name];
					var pce:PropertyChangeEvent = new PropertyChangeEvent(source, _name, old, value);
					IEventDispatcher(source).dispatchEvent(pce);
					if(!pce.isDefaultPrevented())
					{
						if(pce.isNewValueChanged && !validate(value = pce.newValue))
							return false;
						source[_name] = value;
					}
				}else{
					source[_name] = value;
				}
				
				return true;
			}
			return false;
		}
		
		public function toString():String
		{
			return "public var " + _name + ":" + _type;
		}
		
		public function validate(value:*):Boolean
		{
			return value == null || value is _type.classReference;
		}
	}
}